# Order routes
from flask import Blueprint, request, jsonify, session
from app.models.order import (
    create_order, add_order_item, get_orders, get_order_detail, create_order_with_items
)
from app.models.cart import get_cart_items, clear_cart
from app.models.product import get_product_by_id, update_product_stock, check_product_stock
from app.models.user import get_user_by_id, deduct_user_balance, check_user_balance
from app.utils.database import get_db_cursor

orders_bp = Blueprint('orders', __name__)

@orders_bp.route('/orders', methods=['GET'])
def get_orders_api():
    """Get user order list"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    
    try:
        orders, total = get_orders(user_id, page, per_page)
        return jsonify({
            'orders': orders,
            'total': total,
            'page': page,
            'per_page': per_page
        })
    except Exception as e:
        return jsonify({'error': f'Failed to get orders: {str(e)}'}), 500

@orders_bp.route('/orders/<int:order_id>', methods=['GET'])
def get_order_detail_api(order_id):
    """Get order details"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    try:
        order = get_order_detail(order_id, user_id)
        if not order:
            return jsonify({'error': 'Order does not exist'}), 404
        
        return jsonify({'order': order})
    except Exception as e:
        return jsonify({'error': f'Failed to get order details: {str(e)}'}), 500

@orders_bp.route('/orders', methods=['POST'])
def create_order_api():
    """Create order"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    data = request.get_json() or {}
    
    # Get order items (support direct purchase or purchase from cart)
    items = data.get('items', [])
    cart_items = get_cart_items(user_id)
    
    # If no items provided, get from cart
    if not items and not cart_items:
        return jsonify({'error': 'Cart is empty'}), 400
    
    # Verify stock and calculate total price
    total_price = 0
    order_items_data = []
    
    # If items provided, use items; otherwise use cart
    if items:
        for item in items:
            product = get_product_by_id(item['category'], item['product_id'])
            if not product:
                return jsonify({'error': f'Product does not exist: {item["category"]}_{item["product_id"]}'}), 404
            
            # Verify stock
            is_stock_ok, stock_msg = check_product_stock(item['category'], item['product_id'], item['quantity'])
            if not is_stock_ok:
                return jsonify({'error': f'Stock verification failed: {stock_msg}'}), 400
            
            item_price = float(product['price']) * int(item['quantity'])
            total_price += item_price
            
            # Ensure quantity is integer
            quantity = int(item['quantity'])
            order_items_data.append({
                'category': item['category'],
                'product_id': item['product_id'],
                'quantity': quantity,
                'price': float(product['price'])
            })
    else:
        # Get products from cart
        for cart_item in cart_items:
            product = get_product_by_id(cart_item['category'], cart_item['product_id'])
            if not product:
                return jsonify({'error': f'Product does not exist: {cart_item["category"]}_{cart_item["product_id"]}'}), 404
            
            # Verify stock
            is_stock_ok, stock_msg = check_product_stock(cart_item['category'], cart_item['product_id'], cart_item['quantity'])
            if not is_stock_ok:
                return jsonify({'error': f'Stock verification failed: {stock_msg}'}), 400
            
            item_price = float(product['price']) * int(cart_item['quantity'])
            total_price += item_price
            
            # Ensure quantity is integer
            quantity = int(cart_item['quantity'])
            order_items_data.append({
                'category': cart_item['category'],
                'product_id': cart_item['product_id'],
                'quantity': quantity,
                'price': float(product['price'])
            })
    
    # Check user balance
    is_balance_ok, balance_msg = check_user_balance(user_id, total_price)
    if not is_balance_ok:
        return jsonify({'error': f'Balance verification failed: {balance_msg}'}), 400
    
    try:
        # Use transaction to create order
        order_id = create_order_with_items(user_id, total_price, order_items_data)
        
        # Only clear cart when purchasing from cart
        if not items:
            clear_cart(user_id)
        
        return jsonify({
            'message': 'Order created successfully',
            'order_id': order_id
        }), 201
        
    except Exception as e:
        return jsonify({'error': f'Order creation failed: {str(e)}'}), 500

@orders_bp.route('/orders/stats', methods=['GET'])
def get_order_stats():
    """Get order statistics"""
    user_id = session.get('user_id')
    if not user_id:
        return jsonify({'error': 'Please login first'}), 401
    
    conn, cursor = get_db_cursor()
    try:
        cursor.execute("SELECT COUNT(*) FROM orders WHERE user_id = %s", (user_id,))
        total_orders = cursor.fetchone()['count']
        
        cursor.execute("SELECT SUM(total_price) FROM orders WHERE user_id = %s", (user_id,))
        total_spent = cursor.fetchone()['sum'] or 0
        
        return jsonify({
            'total_orders': total_orders,
            'total_spent': float(total_spent)
        })
    finally:
        cursor.close()
        conn.close()
